<template>
  <div class="RoleManage-container">
    <div class="RoleManage-options">
      <el-input
        placeholder="请输入内容"
        style="width:80%;"
        @change="SearchRoles"
        v-model="content"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" style="margin-left:20px" @click="addRole"
        >添加角色</el-button
      >
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>
    <div class="RoleManage-table" v-if="roleList.length">
      <el-table
        :data="roleList"
        border
        @selection-change="handleSelectionChange"
        max-height="80%"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="创建日期" sortable width="180">
          <template slot-scope="scope">
            <svg-icon icon-class="date"></svg-icon>
            <span style="margin-left: 10px">{{
              scope.row.create_time | formatDate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色名" width="80">
          <template slot-scope="scope">
            <el-popover trigger="click" placement="top">
              <div class="permissionList" v-if="permissionList.length">
                <el-tag type="info" v-for="p in permissionList" :key="p.id">
                  {{ p.permission_name }}
                </el-tag>
              </div>
              <div class="permissionList" v-else>
                暂无任何权限
              </div>
              <div slot="reference" class="name-wrapper">
                <el-tag
                  @click="getPermissionListById(scope.row.id)"
                  size="medium"
                  >{{ scope.row.role_name }}</el-tag
                >
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="描述">
          <template slot-scope="scope">
            <span>{{ scope.row.role_description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="warning"
              @click="distributePermission(scope.$index, scope.row)"
              >分配权限</el-button
            >
            <!-- <el-button size="mini"
                     type="info"
                     @click="handleEdit(scope.$index, scope.row)">更改密码</el-button> -->
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        small
        :limit="limit"
        :page-size="limit"
        :current-page="page"
        @current-change="pageChange"
        layout="prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </div>
    <div v-else style="display:flex;justify-content:center">
      <img
        style="width:50%;margin:0 auto"
        src="@/assets/img/search-empty.png"
      />
    </div>
    <DistributeDialog
      @custom-confirm="distributeConfirm"
      @custom-cancel="ditributeDialogClose"
      dialogTitle="分配权限"
      :ids="permissionList"
      type="permission"
      :visible="distributeDialogVisible"
    />
    <EditDialog
      :data="EditForm"
      dialogTitle="编辑角色"
      :visible="EditDialogVisible"
      @custom-confirm="EditConfirm"
      @custom-close="EditDialogClose"
    />
    <AddDialog
      :data="addForm"
      dialogTitle="添加角色"
      :visible="AddDialogVisible"
      @custom-confirm="AddConfirm"
      @custom-close="AddDialogClose"
    />
  </div>
</template>

<script>
import { encryptData } from '@/utils/encrypt'
import EditDialog from '@/components/Dialog/EditDialog'
import AddDialog from '@/components/Dialog/AddDialog'
import DistributeDialog from '@/components/Dialog/DistributeDialog'

export default {
  // 引入组件
  components: {
    EditDialog,
    AddDialog,
    DistributeDialog
  },
  data() {
    return {
      limit: 10,
      page: 1,
      // 权限数据
      permissionList: [],
      count: 0,
      // 角色列表
      roleList: [],
      content: '',
      // 编辑数据
      EditDialogVisible: false,
      formLabelWidth: '80px',
      // 编辑表单
      EditForm: {},
      // 添加表单
      addForm: {
        name: '',
        description: ''
      },
      // 添加角色窗口显示标志位
      AddDialogVisible: false,
      // 分配权限窗口显示标志位
      distributeDialogVisible: false,
      // 分配权限参数
      distributeForm: {
        permission_ids: '',
        role_id: ''
      },
      selectedRoles: ''
    }
  },
  created() {
    // 获取角色列表
    this.$nextTick(() => {
      this.getRoleList()
    })
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const { limit, page } = this
      const res = await this.$API.role.getRoleList(limit, page)
      if (res.status == 200) {
        this.count = res.data.count
        this.roleList = res.data.payload
      }
    },
    // 添加角色确认功能回调
    async AddConfirm(formData) {
      // 整理数据
      const datas = this.$qs.stringify(formData)
      const res = await this.$API.role.addRole(datas)
      if (res.status == 200) {
        this.$message.success('添加成功')
        // 初始化数据
        this.AddDialogVisible = false
        this.content = ''
        this.getRoleList()
      }
    },
    // 添加角色窗口关闭回调
    AddDialogClose() {
      this.AddDialogVisible = false
    },
    // 页数改变
    pageChange(page) {
      this.page = page
      this.getRoleList()
    },
    // 编辑角色
    handleEdit(id, role) {
      console.log(role)
      // 整理数据
      let datas = {
        id: role.id,
        role_name: role.role_name,
        role_description: role.role_description
      }
      // 获取数据
      this.EditForm = datas
      this.EditDialogVisible = true
    },
    // 删除角色
    handleDelete(id, role) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$API.role.DeleteRole(role.id)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getRoleList()
            this.content = ''
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索角色
    async SearchRoles() {
      this.page = 1
      const { content, page, limit } = this
      console.log(content, page, limit)
      // 如果不存在搜索内容就获取全部
      if (!this.content) return this.getRoleList()
      const res = await this.$API.role.SearchRoles(content, limit, page)
      // 如果不存在角色就显示空
      if (!res.data) this.roleList = []
      console.log(res)
      if (res.status == 200) {
        this.roleList = res.data.payload
        this.count = res.data.count
      }
    },
    // 关闭对话框
    EditDialogClose() {
      this.EditDialogVisible = false
    },
    // 确定编辑
    async EditConfirm(formData) {
      // 整理数据
      let { id } = formData
      const datas = {
        role_id: id,
        ...formData
      }
      const res = await this.$API.role.EditRole(this.$qs.stringify(datas))
      if (res.status == 200) {
        this.$message.success('编辑成功')
        // 初始化数据
        this.EditDialogVisible = false
        this.content = ''

        this.getRoleList()
        this.EditForm = {}
      } else {
        this.$message.error('编辑失败')
      }
    },
    // 添加角色
    addRole() {
      this.AddDialogVisible = true
    },
    // 通过角色id获取用户的权限
    async getPermissionListById(id) {
      const res = await this.$API.role.getPermissionListById(id)
      // 如果不存在权限就将权限列表清空
      if (!res.data) return (this.permissionList = [])
      if (res.status == 200) {
        this.permissionList = res.data
      }
    },
    // 关闭分配角色窗口回调
    ditributeDialogClose() {
      this.distributeDialogVisible = false
    },
    // 分配权限
    async distributePermission(index, role) {
      // 获取当前分配的用户所有角色
      this.getPermissionListById(role.id)
      this.distributeForm.role_id = role.id
      this.distributeDialogVisible = true
    },
    // 确认分配权限功能回调
    async distributeConfirm(permission_ids) {
      // 整理数据
      this.distributeForm.permission_ids = permission_ids
      const res = await this.$API.role.bindPermission(
        this.$qs.stringify(this.distributeForm)
      )
      if (res.status == 200) {
        this.$message.success('分配权限成功')
        // 初始化数据
        this.getRoleList()
        this.content = ''
        this.distributeDialogVisible = false
      }
    },
    // 多选项切换时
    handleSelectionChange(selection) {
      this.selectedRoles = selection
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRoles.length === 0) {
        this.$message.warning('请选择要删除的文章')
        return
      }

      this.$confirm('此操作将永久删除选中的文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const roleIds = this.selectedRoles.map(role => role.id)
          const formData = new FormData()
          formData.append('ids', roleIds.join(','))
          const res = await this.$API.role.BatchDeleteRole(formData)
          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.getRoleList()
            this.content = ''
            this.selectedRoles = []
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    }
  }
}
</script>
<style scoped>
.RoleManage-container {
  width: 100%;
  padding: 20px;
}
.RoleManage-options {
  margin-bottom: 20px;
}
.RoleManage-table {
  width: 100%;
  margin: 10px auto;
}
</style>